package com.yueyang.domain;

import org.bson.types.Binary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

/**
 *  base64工具类
 *  @author dcd
 *  @date 2019年12月31日15:59:09
 */
public class Base64Utils {

    public  final static String FILE_PATH = "d:/hyUpload/"; //图片上传的地址
    /**
     * 本地图片转换成base64字符串
     * @param imgFile	图片本地路径
     * @return
     *
     * @author ZHANGJL
     * @dateTime 2018-02-23 14:40:46
     */
    public static Binary ImageToBase64ByLocal(String imgFile) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理

        InputStream in = null;
        byte[] data = null;

        // 读取图片字节数组
        try {
            in = new FileInputStream(imgFile);

            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
//        BASE64Encoder encoder = new BASE64Encoder();

//        return encoder.encode(data);// 返回Base64编码过的字节数组字符串
        return new Binary(data);
    }


    /**
     * 在线图片转换成base64字符串
     *
     * @param imgURL	图片线上路径
     * @return
     *
     * @dateTime 2018-02-23 14:43:18
     */
    public static String ImageToBase64ByOnline(String imgURL) {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(imgURL);
            byte[] by = new byte[1024];
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            // 将内容读取内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            // 关闭流
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data.toByteArray());
    }


    /**
     * base64字符串转换成图片
     * @param imgStr		base64字符串
     * @return
     *
     * @dateTime 2018-02-23 14:42:17
     */
    public static String base64ToImage(String imgStr) { // 对字节数组字符串进行Base64解码并生成图片

        String imgExt = "";//保存图片格式
        String fileName = "";//文件名
        String filePath1  = "";
        if (imgStr.length()>10000) { // 判断图像数据是否为空
            BASE64Decoder decoder = new BASE64Decoder();
            imgExt = getImgFormat(imgStr);//获取图片格式
            imgStr = transformImg(imgStr);
            try {
                // Base64解码
                byte[] b = decoder.decodeBuffer(imgStr);
                for (int i = 0; i < b.length; ++i) {
                    if (b[i] < 0) {// 调整异常数据
                        b[i] += 256;
                    }
                }
                File uploadDirectory = new File(FILE_PATH);
                if (uploadDirectory.exists()) {
                    if (!uploadDirectory.isDirectory()) {
                        uploadDirectory.delete();
                    }
                } else {
                    uploadDirectory.mkdir();
                }
//                fileName = DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_PATTERN) + RandNumber.rand(6) + "." + imgExt; // 新文件名
                filePath1 = FILE_PATH + fileName;
                OutputStream out = new FileOutputStream(filePath1);//上传
                out.write(b);
                out.flush();
                out.close();
                return fileName;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return fileName;
    }

    public static String transformImg(String imgStr){
        if (imgStr.indexOf("data:image/png;") != -1) {
            imgStr = imgStr.replace("data:image/png;base64,", "");
        } else if (imgStr.indexOf("data:image/jpeg;") != -1) {
            imgStr = imgStr.replace("data:image/jpeg;base64,", "");
        } else if(imgStr.indexOf("data:image/gif;") != -1){
            imgStr = imgStr.replace("data:image/gif;base64,", "");
        } else if(imgStr.indexOf("data:image/bmp;") != -1){
            imgStr = imgStr.replace("data:image/bmp;base64,", "");
        } else if(imgStr.indexOf("data:image/jpg;") != -1){
            imgStr = imgStr.replace("data:image/jpg;base64,", "");
        }
        return imgStr;
    }

    //获取图片格式
    public static String getImgFormat(String imgStr){
        String imgStr1 = "";
        if(imgStr == "" || imgStr == null){
            return imgStr1;
        }
        if (imgStr.indexOf("data:image/png;") != -1) {
            imgStr1 = "png";
        } else if (imgStr.indexOf("data:image/jpeg;") != -1) {
            imgStr1 = "jpeg";
        } else if(imgStr.indexOf("data:image/gif;") != -1){
            imgStr1 = "gif";
        } else if(imgStr.indexOf("data:image/bmp;") != -1){
            imgStr1 = "bmp";
        } else if(imgStr.indexOf("data:image/jpg;") != -1){
            imgStr1 = "jpg";
        }
        return imgStr1;
    }
}
